package bigdata;

import java.util.Collection;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.query.Predicate;
import com.hazelcast.query.Predicates;

public class LiteMember {
	private static final int TOTAL = 10000;
	private final static Logger logger = LoggerFactory.getLogger(LiteMember.class);

	public static void main(String[] args) throws InterruptedException {
		Config config = new Config();
		config.getSerializationConfig().addPortableFactory(1, new MyPortableFactory());
		config.setLiteMember(true);
		HazelcastInstance hz = Hazelcast.newHazelcastInstance(config);

		IMap<Integer, Rule> ruleMap = hz.getMap("ruleMap");
		query(ruleMap);
		kv(ruleMap);

		System.exit(0);
	}

	public static void query(IMap<Integer, Rule> ruleMap) {
		long start = System.currentTimeMillis();
		int total = TOTAL;
		int match = 0;
		for (int i = 0; i < total; i++) {
			Random random = new Random(start);
			int tel = random.nextInt() % 100000000;
			Predicate<?, ?> p = Predicates.equal("tel", String.valueOf(tel));
			Collection<Rule> result = ruleMap.values(p);
			if (result.size() > 0) {
				match++;
				// logger.info("tel:{},result:{}", tel, result.size());
				// for (Iterator<Rule> item = result.iterator();
				// item.hasNext();) {
				// Rule rule = item.next();
				// logger.info("tel:{}", rule.getTel());
				// }
				// Thread.sleep(1000);
			}
		}

		long cost = (System.currentTimeMillis() - start);
		logger.info("query {} time, get {} times, in {} ms", total, match, cost);
	}

	public static void kv(IMap<Integer, Rule> ruleMap) {
		long start = System.currentTimeMillis();
		int total = TOTAL;
		int match = 0;
		for (int i = 0; i < total; i++) {
			Random random = new Random(start);
			int tel = random.nextInt() % 100000000;
			Rule rule = ruleMap.get(tel);
			if (rule != null) {
				match++;
			}
		}

		long cost = (System.currentTimeMillis() - start);
		logger.info("kv {} time, get {} times, in {} ms", total, match, cost);
	}
}
